const LoginKey = "Logined-User"
const LoginKey2 = "Logined-User-2"
const LoginKey3 = "Logined-User-3"

function getKey (type){
    if(type==2){
        return LoginKey2
    } else if(type==3){
        return LoginKey3
    }
    return LoginKey
}
export function setLoginedUser(user, type) {
     
    if(user) {
        wx.setStorageSync(getKey(type), JSON.stringify(user))
    }
}

export function getLoginedUser(type) {
    let user =  wx.getStorageSync(getKey(type))
    if(user){
        user = JSON.parse(user)
        return user
    }
    return null
}

export function removeLoginedUser(type) {
    wx.removeStorageSync(getKey(type))
}

import userApi from '@/api/api-user'
import store from '@/store'
export function login(detail, vm, callback, type){
    wx.login({
        success (res) {
            if (res.code) {
                userApi.LoginByWeChat({
                    code: res.code
                }).then(data => {
                    if(data.code == 0){
                        data = data.result
                        let userInfo = data.userinfo
                        userInfo.accessToken = data.token
                        userInfo.openid = data.openid
                        userInfo.sessionId = data.sessionId
                        store.dispatch('SetLoginUser', userInfo).then(()=>{
                            if(callback)
                                callback(detail, type)
                        })
                    }
                })
            } else {
                wx.showToast({
                    title: "微信登录失败",
                    icon: 'none',
                    duration: 2000
                })
            }
        }
    })
}